package com.xqboss.apps.service.order;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.member.SysUserNft;
import com.xqboss.apps.domain.nft.NftDispatchRecord;
import com.xqboss.apps.domain.order.OrderItem;
import com.xqboss.apps.enums.nft.NftDispatchSourceEnum;
import com.xqboss.apps.mapper.order.NftDispatchRecordMapper;
import com.xqboss.apps.vo.user.UserNFTItemVo;
import com.xqboss.common.exception.ServiceException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Trent
 * @date 2023/8/29
 */
@Service
public class NftDispatchRecordService extends ServiceImpl<NftDispatchRecordMapper, NftDispatchRecord> {

    /**
     * 获取主订单号的nft分配信息
     * @param orderMainId
     * @return
     */
    public List<UserNFTItemVo> getRecordByOrderId(NftDispatchSourceEnum source, Long orderMainId){
        return baseMapper.selectByOrderMainId(source, orderMainId);
    }

    /**
     * 获取子订单号的nft分配信息
     * @param orderItemId
     * @return
     */
    public List<UserNFTItemVo> getRecordByOrderItemId(NftDispatchSourceEnum source, Long orderItemId){
        return baseMapper.selectByOrderItemId(source, orderItemId);
    }

    /**
     * 存储NFT记录
     * @param orderItem
     * @param userNft
     */
    public void addMarketRecord(OrderItem orderItem, SysUserNft userNft){
        NftDispatchRecord record = new NftDispatchRecord();
        record.setDispatchSource(NftDispatchSourceEnum.MARKET);
        record.setUserNftId(userNft.getId());
        record.setUserId(userNft.getUserId());
        record.setOrderMainId(orderItem.getOrderMainId());
        record.setOrderItemId(orderItem.getId());
        record.setNftId(userNft.getNftId());
        record.setNftNumberId(userNft.getNftNumberId());
        record.setNftType(userNft.getNftType());
        boolean saved = save(record);
        if (!saved) {
            throw new ServiceException("操作失败！");
        }
    }

    /**
     * 获取主订单号的nft分配信息 （藏品转赠）
     * @param source
     * @param remark
     * @return
     */
    public List<UserNFTItemVo> getRecordByTransfer(NftDispatchSourceEnum source, String remark, Long sourceId) {
        // 将remark逗号分隔的字符串转为list集合
        List<Long> nftNumberIds = Arrays.stream(remark.split(","))
                .map(Long::valueOf)
                .collect(Collectors.toList());
        List<UserNFTItemVo> userNftItemVos = baseMapper.selectByTransfer(source, nftNumberIds, sourceId);
        // 根据 nftNumberValue 列表去重复
        return userNftItemVos.stream().distinct().collect(Collectors.toList());
    }
}
